package iscas;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.util.ArrayList;

public class LocalListState<T> extends RedisLocalState {
    ArrayList<T> local = new ArrayList<>();
    final Object mergeLock = new Object();

    public LocalListState(String name, long period) {
        super(name, period);
    }

    public void add(T v) {
        synchronized (mergeLock) {
            local.add(v);
        }
    }

    @Override
    boolean isEmpty() {
        synchronized (mergeLock) {
            return local.isEmpty();
        }
    }

    @Override
    public void merge(Jedis jedis) {
        ArrayList<T> temp;
        synchronized (mergeLock) {
            temp = local;
            local = new ArrayList<>();
        }
        Pipeline pipeline = jedis.pipelined();
        temp.forEach(e -> pipeline.rpush(name, e.toString()));
        pipeline.sync();
    }
}
